# original version by Michael Hawthornthwaite - Acid Computer Services (www.acidcs.co.uk)

#import cgi
import os
import logging
#import the HTTP, DOM and ConfigParser modules needed
import httplib, ConfigParser
from xml.dom.minidom import parse, parseString, Node


class Api(object):
  def __init__(self):
    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    devID = config.get('Keys', 'Developer')
    appID = config.get('Keys', 'Application')
    certID = config.get('Keys', 'Certificate')
    serverUrl = config.get('Server', 'URL')
    serverDir = config.get('Server', 'Directory')
    userToken = config.get('Authentication', 'Token')
    #eBay Call Variables
    #0 = US, 2 = Canada, 3 = UK, ....
    siteID = '0'
    #verb specifies the name of the call
    verb = 'egroseille'
    #The API level that the application conforms to
    compatabilityLevel = '433'
    logging.basicConfig(level=logging.INFO,
                      format='%(asctime)s %(name)-6s %(levelname)-8s %(message)s',
                      filename='ebay.log') 
  
  # Build together the required headers for the HTTP request to the eBay API
  def buildHttpHeaders(self):
      return {'X-EBAY-API-COMPATIBILITY-LEVEL': self.compatabilityLevel,	
                 'X-EBAY-API-DEV-NAME': self.devID,
                 'X-EBAY-API-APP-NAME': self.appID,
                 'X-EBAY-API-CERT-NAME': self.certID,
                 'X-EBAY-API-CALL-NAME': self.verb,
                 'X-EBAY-API-SITEID': self.siteID,
                 'Content-Type': 'text/xml'}
      
  # Build the body of the call (in XML) incorporating the required parameters to pass
  def buildRequestXml(self, query):
      return "<?xml version='1.0' encoding='utf-8'?>"+\
                "<GetSearchResultsRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">"+\
                "<RequesterCredentials><eBayAuthToken>" + self.userToken + "</eBayAuthToken></RequesterCredentials>" + \
                "<Query>" + query + "</Query>"+\
                "</GetSearchResultsRequest>"

  def query(self, query):
    # specify the connection to the eBay Sandbox environment
    connection = httplib.HTTPSConnection(self.serverUrl)

    # specify a POST with the results of generateHeaders and generateRequest
    connection.request('POST', self.serverDir, buildRequestXml(query), buildHttpHeaders())
    response = connection.getresponse()

    # if response was unsuccessful, log message
    if response.status != 200:
      logging.error('Error sending request:%s' % response.reason)
      return 0
    else:
      # store the response data and close the connection
      data = response.read()
      connection.close()
      
      # parse the response data into a DOM
      response = parseString(data)

      # check for any Errors
      errorNodes = response.getElementsByTagName('Errors')
      if (errorNodes != []): #there are errors
        for error in errorNodes:
          #output the error code and short message (with special characters replaces)
          logging.warning('Error code:%s' % ((error.getElementsByTagName('ErrorCode')[0]).childNodes[0]).nodeValue)
      else: 
        #get all the Items returned as results
        return response.getElementsByTagName('Item');

    # force garbage collection of the DOM object
    response.unlink()
